import {HTTP} from '../util/http'

class Classic extends HTTP {

    getLatest() {

        return new Promise(
            (resolve, reject) => {
                this.request({
                    url: '/classic/latest',
                    success: (res) => {

                        this._setLatestIndex(res.index)
                        let key = this._getKey(res.index)
                        wx.setStorageSync(key, res)
                        resolve(res)

                    }
                })
            }
        )

    }


     getClassic(index, status) {

        let key = status === 'next' ? this._getKey(index + 1) : this._getKey(index - 1)
        //
        let classic = wx.getStorageSync(key)
        if (!classic) {
            return new Promise(
                (resolve, reject) => {
                    this.request({
                        url: `/classic/${index}/${status}`,
                        success: (res) => {
                            wx.setStorageSync(this._getKey(res.index), res)
                            // this._setLatestIndex(index)
                            resolve(res)
                        }
                    })
                }
            )
        } else {
            return new Promise(
                (resolve, reject) => {
                    resolve(classic)
                }
            )

        }


    }


    isFirst(index) {

        return index === 1
    }

    isLatest(index) {
        return index === this._getLatestIndex()
    }

    _setLatestIndex(index) {
        wx.setStorageSync("latest", index)
    }

    _getLatestIndex() {
        return wx.getStorageSync("latest")
    }

    _getKey(index) {
        return "classic-" + index

    }

}

export {Classic}
